<script>
import { getDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
import {
  getEmployee,
  exportEmployee,
  deleteEmployee,
  enabledRoleList,
  assignRole,
  getEmployeeDetail
} from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel from '@/views/employee/components/import-excel'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      showExcelDialog: false, // 控制导入excel弹窗
      showRoleDialog: false, // 控制分配角色弹窗
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      queryParams: {
        page: 1,
        pagesize: 10,
        departmentId: null,
        keyword: ''
      },
      employeeList: [], // 员工列表
      enabledRoleList: [], // 可用的角色列表
      roleIds: [], // 用户绑定的角色列表
      currentEmployeeId: null
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 获取部门树形列表
    async getDepartment() {
      const result = await getDepartment()
      this.depts = transListToTreeData(result, 0)
      this.queryParams.departmentId = this.depts[0].id
      // 树节点渲染数据是异步的 这里必须等所有树节点全部渲染完毕才能赋值
      this.$nextTick(() => {
        // setCurrentKey必须设置node-key node-key必须是每条数据唯一的值 id、name、code都可以
        this.$refs.deptRef.setCurrentKey(this.queryParams.departmentId)
        // 这里调用员工列表接口
        this.getEmployee()
      })
    },
    // 选中部门节点后 回调该方法
    clickChange(row) {
      this.queryParams.departmentId = row.id
      this.queryParams.page = 1
      this.getEmployee()
    },
    // 获取员工列表
    async getEmployee() {
      const { rows, total } = await getEmployee(this.queryParams)
      this.employeeList = rows
      this.queryParams.total = total
    },
    // 点击页数回调方法
    changePage(newPage) {
      this.queryParams.page = newPage
      this.getEmployee()
    },
    // 关键词搜索
    inputChange() {
      this.queryParams.page = 1
      this.getEmployee()
    },
    // 导出员工
    async exportEmployee() {
      const result = await exportEmployee()
      FileSaver.saveAs(result, '员工信息.xlsx')
    },
    // 删除员工
    async delEmployee(id) {
      await deleteEmployee(id)
      // 判断是否是最后一条记录
      if (this.queryParams.page > 1 && this.employeeList.length === 1) {
        this.queryParams.page--
      }
      this.getEmployee()
      this.$message.success('删除员工成功')
    },
    // 获取用户角色
    async getEmployeeRole(id) {
      this.currentEmployeeId = id
      this.enabledRoleList = await enabledRoleList()
      const { roleIds } = await getEmployeeDetail(this.currentEmployeeId)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    // 分配角色
    async assignRole() {
      await assignRole({ id: this.currentEmployeeId, roleIds: this.roleIds })
      this.showRoleDialog = false
      this.$message.success('分配角色成功')
    }
  }
}
</script>

<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @change="inputChange" />
        <!-- 树形组件 -->
        <el-tree
          ref="deptRef"
          highlight-current
          default-expand-all
          :expand-on-click-node="false"
          :data="depts"
          :props="defaultProps"
          node-key="id"
          @current-change="clickChange"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :header-cell-style="{ background: '#f5f6f8' }" :data="employeeList">
          <el-table-column label="头像" align="center" prop="staffPhoto">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="{row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template v-slot="{ row }">
              <el-button type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" @click="getEmployeeRole(row.id)">角色</el-button>
              <el-popconfirm style="margin-left: 10px" title="确定删除该员工吗？" @onConfirm="delEmployee(row.id)">
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!--      分页插件-->
        <div style="margin-top: 10px;text-align: right">
          <el-pagination
            layout="total, prev, pager, next"
            :page-size="queryParams.pagesize"
            :current-page="queryParams.page"
            :total="queryParams.total"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployee" />

    <!--角色弹出框-->
    <el-dialog title="分配角色" :visible.sync="showRoleDialog" width="50%">
      <el-checkbox-group v-model="roleIds">
        <!--label是存储选中的角色的值，存在roleIds中-->
        <el-checkbox v-for="item in enabledRoleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <!--slot="footer"可以将盒子放在底部-->
      <el-row slot="footer" style="width: 100%">
        <el-col style="text-align: center">
          <el-button type="primary" size="small" @click="assignRole">确 定</el-button>
          <el-button size="small" @click="showRoleDialog=false">取 消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.container {
  padding: 20px;
  .app-container {
    background: #fff;
    display: flex;
    .left {
      width: 280px;
      padding: 20px;
      border-right: 1px solid #eaeef4;
    }
    .right {
      flex: 1;
      padding: 20px;
      .opeate-tools {
        margin:10px ;
      }
      .username {
        height: 30px;
        width: 30px;
        line-height: 30px;
        text-align: center;
        border-radius: 50%;
        color: #fff;
        background: #04C9BE;
        font-size: 12px;
        display:inline-block;
      }
    }
  }
}

</style>
